//
//  FJHomeDetailTableViewCell.swift
//  FruitJuice
//
//  Created by Rae on 2024/1/3.
//

import UIKit
import JXBanner
import JXPageControl

class FJHomeDetailTableViewCell: UITableViewCell {

    private let iconImageView       = c_make_ex(UIImageView.self)
        .mode(.scaleAspectFill).corner(8).end()
    private let nameLabel           = c_make_ex(UILabel.self)
        .color(.black).font(18.font_bold).end()
    private let timeLabel           = c_make_ex(UILabel.self)
        .color(.black).font(14.font_regular).end()
    private let contentLabel        = c_make_ex(UILabel.self)
        .color(.black).font(17.font_regular).line(0).end()
    private let collectionView = UICollectionView(frame: .zero, collectionViewLayout: UICollectionViewFlowLayout())
    private let otherLabel        = c_make_ex(UILabel.self)
        .color("#FF9133").font(18.font_medium).alignment(.center)
        .corner(12.5).bgColor("#EFEFEF").end()
    private lazy var linearBanner: JXBanner = {[weak self] in
        let banner = JXBanner()
        banner.placeholderImgView.image = UIImage(named: "FJ_Common_placeholder")
        banner.indentify = "linearBanner"
        banner.delegate = self
        banner.dataSource = self
        banner.isUserInteractionEnabled = false
        return banner
    }()
    private let titleLabel        = c_make_ex(UILabel.self)
        .color(.black).font(18.font_semiBold)
        .text("Comminicate：").end()
    lazy var commitView: FJChatTextView = {
        let view = FJChatTextView()
        view.backgroundColor = "#EFEFEF".toColor
        view.textContainerInset = UIEdgeInsets(top: 10.Fit, left: 15.Fit, bottom: 10.Fit, right: 15.Fit)
        view.tintColor = .black
        view.textColor = .black
        view.placeHolderColor = "#B5B5B5".toColor
        view.placeHolder = "Let’s share the experience"
        view.placeholderFont = 15.font_medium
        view.returnKeyType = .send
        view.font = 15.font_medium
        view.layer.cornerRadius = 20
        view.layer.masksToBounds = true
        view.delegate = self
        return view
    }()
    
    private var materialArray = [String]()
    private var imgDataArr = [String]()
    
    var sentCommitClosure: ((_ msg: String) -> Void)?
    
    var model:InfoUtil.room?{
        didSet{
            
            guard let md = model else {
                return
            }
            
            contentLabel.text = md.descInfo
            if let headImg = md.info3 {
                iconImageView.loadImage(url: headImg,placehold: "FJ_Common_avator")
            }else{
                iconImageView.image = "FJ_Common_avator".toImage
            }
            if let name = md.info2 {
                nameLabel.text = name
            }else{
                nameLabel.text = "Fruit Juice"
            }
            if let other = md.info1, other.count > 0 {
                otherLabel.text = other
            }else{
                otherLabel.text = "others"
            }
            if let time = md.info4 {
                timeLabel.text = time
            }else{
                timeLabel.text = "2024-01-03"
            }
            let array = md.icon!.components(separatedBy: ",")
            imgDataArr = array
            var materialArr = [String]()
            let fruitArr = md.info!.components(separatedBy: ",")
            let greenArr = md.info0!.components(separatedBy: ",")
            materialArr.append(contentsOf: fruitArr)
            materialArr.append(contentsOf: greenArr)
            materialArray = materialArr
            
            linearBanner.reloadView()
            collectionView.reloadData()
        }
    }
    
    
    override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        selectionStyle = .none
        backgroundColor = .clear
        contentView.backgroundColor = .clear
        
        contentView.subviews {
            iconImageView
            nameLabel
            timeLabel
            contentLabel
            collectionView
            otherLabel
            linearBanner
            titleLabel
            commitView
        }
        iconImageView.leading(15).top(7.5).size(50)
        nameLabel.leading(75).width(95).top(13)
        timeLabel.leading(75)
        timeLabel.Top == nameLabel.Bottom + 0.5
        contentLabel.trailing(15).leading(15)
        contentLabel.Top == iconImageView.Bottom + 15
        collectionView.leading(0).trailing(0).height(60)
        collectionView.Top == contentLabel.Bottom + 10
        otherLabel.leading(15).width(120).height(40)
        otherLabel.Top == collectionView.Bottom + 10
        linearBanner.leading(0).trailing(0).height(300)
        linearBanner.Top == otherLabel.Bottom + 10
        titleLabel.leading(15)
        titleLabel.Top == linearBanner.Bottom + 20
        commitView.trailing(15).height(40).width(205).bottom(12.5)
        commitView.CenterY == titleLabel.CenterY

        let layout = UICollectionViewFlowLayout()
        layout.scrollDirection = .horizontal
        layout.minimumLineSpacing = 10
        layout.minimumInteritemSpacing = 10
        layout.itemSize = CGSize(width: 60, height: 60)
        layout.sectionInset = UIEdgeInsets(top: 0, left: 15.0, bottom: 0, right: 0)
        collectionView.style { v in
            v.collectionViewLayout = layout
            v.backgroundColor = .clear
            v.register(FJPushMaterialsItemCell.self, forCellWithReuseIdentifier: FJPushMaterialsItemCell.description())
            v.showsHorizontalScrollIndicator = false
            v.delegate = self
            v.dataSource = self
        }
        iconImageView.isUserInteractionEnabled = true
        let tap = UITapGestureRecognizer(target: self, action: #selector(pushToOthersInfo))
        iconImageView.addGestureRecognizer(tap)
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func awakeFromNib() {
        super.awakeFromNib()
        // Initialization code
    }

    override func setSelected(_ selected: Bool, animated: Bool) {
        super.setSelected(selected, animated: animated)

        // Configure the view for the selected state
    }

}

//MARK: action
extension FJHomeDetailTableViewCell{
    
    @objc private func pushToOthersInfo(){
        
    }
}

//MARK: Delegate, DataSource
extension FJHomeDetailTableViewCell: UICollectionViewDelegate, UICollectionViewDataSource, JXBannerDataSource, JXBannerDelegate, UITextViewDelegate{
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {

        materialArray.count
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        
        guard let item = collectionView.dequeueReusableCell(withReuseIdentifier: FJPushMaterialsItemCell.description(), for: indexPath) as? FJPushMaterialsItemCell else { return UICollectionViewCell() }
        item.imgStr = materialArray[indexPath.row]
        return item
    }
    
    func jxBanner(numberOfItems banner: JXBannerType) -> Int {
        return imgDataArr.count
    }

    func jxBanner(_ banner: JXBannerType) -> (JXBannerCellRegister) {

        return JXBannerCellRegister(type: FJBannerCell.self,
                                        reuseIdentifier: "FJBannerCell")
    }

    func jxBanner(_ banner: JXBannerType,
                  cellForItemAt index: Int,
                  cell: UICollectionViewCell) -> UICollectionViewCell {

        guard let imageCell = cell as? FJBannerCell else {
            return cell
        }
        imageCell.imgUrl = imgDataArr[index]
        return imageCell
    }

    func jxBanner(_ banner: JXBannerType,
                  params: JXBannerParams) -> JXBannerParams {

        return params
            .timeInterval(2)
            .cycleWay(.forward)
            .isAutoPlay(false)
    }

    func jxBanner(pageControl banner: JXBannerType,
                  numberOfPages: Int,
                  coverView: UIView,
                  builder: JXBannerPageControlBuilder) -> JXBannerPageControlBuilder {

        let pageControl = JXPageControlScale()
        pageControl.contentMode = .bottom
        pageControl.activeSize = CGSize(width: 15, height: 6)
        pageControl.inactiveSize = CGSize(width: 6, height: 6)
        pageControl.activeColor = .white
        pageControl.inactiveColor = .white.alpha(0.4)
        pageControl.columnSpacing = 0
        pageControl.isAnimation = true
        builder.pageControl = pageControl
        builder.layout = {
            pageControl.snp.makeConstraints { (maker) in
                maker.centerX.equalTo(coverView)
                maker.bottom.equalTo(coverView.snp.bottom).offset(-20)
                maker.height.equalTo(20)
            }
        }
        return builder

    }
    
    // UITextViewDelegate 方法，用于监听文本变化
    func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
        // 检查输入的 text 是否包含换行符
        if text == "\n" {
            // 在这里处理 Return 按钮的点击事件
            handleReturnButtonTap()
            // 返回 false，阻止换行符的插入
            return false
        }
        // 允许其他文本的插入
        return true
    }
    
    // 处理 Return 按钮的点击事件
    func handleReturnButtonTap() {
        // 在这里添加你的逻辑
        if let msg = commitView.text, msg.count > 0 {
            commitView.text = ""
            commitView.resignFirstResponder()
            sentCommitClosure?(msg)
        }else{
            "Please enter a comment".toast_error
        }
    }
}

